var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs = require('ejs');
var vertoken = require('./public/javascripts/token')
// app.js中部分代码
var {expressjwt} = require('express-jwt');



var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var topicRouter = require('./routes/topic');
var bannerRouter = require('./routes/banner');
var learnRouter = require('./routes/learn');
var typeRouter = require('./routes/type');
var linkRouter = require('./routes/link');
var imgRouter = require('./routes/img');
var msgRouter = require('./routes/message');
var comRouter = require('./routes/comment');
var hotSearchRouter = require('./routes/hotSearch');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');

app.engine('html', ejs.__express);
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//***********
// 解析token获取用户信息
app.use(function(req, res, next) {
  var token = req.headers['authorization'];
  if(token == undefined){
    return next();
  }else{
    vertoken.verToken(token).then((data)=> {
      req.data = data;
      return next();
    }).catch((error)=>{
      return next();
    })
  }
});




//验证token是否过期并规定哪些路由不用验证
app.use(expressjwt({
  secret: 'mes_qdhd_mobile_xhykjyxgs',
  algorithms: ['HS256']
}).unless({
  path: ['/hot','/login','/register','/topic/typelist','/topic','/','/admin','/banner','/learn','/link','/type','/link/type','/img','/message','/comment/all','comment']//除了这个地址，其他的URL都需要验证
}));
// 当token失效返回提示信息
app.use(function(err, req, res, next) {
  if (err.status == 401) {
    return res.status(200).send({code:401,msg:'token失效'});
  }
});


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/topic', topicRouter);
app.use('/banner', bannerRouter);
app.use('/type', typeRouter);
app.use('/learn', learnRouter);
app.use('/link', linkRouter);
app.use('/img', imgRouter);
app.use('/message', msgRouter);
app.use('/comment', comRouter);
app.use('/hot', hotSearchRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {

  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
